import traceback

from fastapi import Depends, Body
from sqlalchemy.orm import Session

from logs.log import logger
from middlewares.middlewares import generate_response
from routes.routers import v2, v1_admin
from schemas import crud, schemas, models
from schemas.database import get_db
from schemas.models import UserSubscription


# 用户 CRUD
@v1_admin.post("/users/")
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    try:
        db_user = crud.get_user_by_username(db, username=user.username)
        if db_user:
            return generate_response(data=None, status_code=500, message="用户名已存在")
        return generate_response(crud.create_user(db=db, user=user), 200)
    except Exception as e:
        return generate_response({}, 500, str(e))


@v1_admin.get("/users/")
def read_users(page: int = 1, num: int = 10, db: Session = Depends(get_db)):
    skip = (page - 1) * num
    users = crud.get_list_data(db, skip=skip, limit=num)
    return generate_response(users, 200)

@v2.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        return generate_response(data=None, status_code=404, message="用户不存在")
    return db_user

@v2.put("/users/{user_id}")
def update_user(user_id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)):
    try:
        db_user = crud.get_user(db, user_id=user_id)
        if db_user is None:
            return generate_response(data=None, status_code=404, message="用户不存在")
        user_email = user.email
        user.email = None
        result = crud.update_user(db=db, user_id=user_id, user=user)
        crud.update_user_email(db, user_id=user_id, email=user_email)
        return generate_response(result, 200)
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))


@v2.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
    try:
        db_user = crud.get_user(db, user_id=user_id)
        if db_user is None:
            return generate_response(data={}, status_code=200, message="用户不存在")
        result =  crud.delete_user(db=db, user_id=user_id)
        return generate_response(result, 200)
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response(data=None, status_code=500, message=str(e))

@v2.get("/users/{user_id}/point_logs")
def read_user_point_logs(user_id: int, page: int = 1, num: int = 10, db: Session = Depends(get_db)):
    try:
        skip = (page - 1) * num
        user = crud.get_user(db, user_id=user_id)
        if user is None:
            return generate_response(data=None, status_code=404, message="用户不存在")
        
        point_logs = crud.get_user_point_logs(db, user_id=user_id, skip=skip, limit=num)
        return generate_response(point_logs, 200, "成功")
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))

@v2.post("/users/{user_id}/subscriptions")
def update_user_subscriptions(user_id: int, subscription_data: dict = Body(...), db: Session = Depends(get_db)):
    try:
        print(user_id, subscription_data)
        user = crud.get_user(db, user_id=user_id)
        if user is None:
            return generate_response(data=None, status_code=404, message="用户不存在")
        
        subscription_ids = subscription_data.get("subscription_ids", [])
        if not isinstance(subscription_ids, list):
            return generate_response(data=None, status_code=400, message="subscription_ids 必须是一个列表")
        
        subscriptions = db.query(models.Subscription).filter(models.Subscription.id.in_(subscription_ids)).all()
        if len(subscriptions) != len(subscription_ids):
            return generate_response(data=None, status_code=404, message="部分订阅不存在")

        # 清除现有的订阅
        user.subscriptions.clear()

        # 创建新的订阅关系记录
        new_subscriptions = [
            UserSubscription(user_id=user.id, subscription_id=subscription.id)
            for subscription in subscriptions
        ]

        # 将新的订阅关系记录添加到会话
        db.bulk_save_objects(new_subscriptions)
        db.commit()
        db.refresh(user)
        
        return generate_response({"username": user.username}, 200, "成功更新用户订阅")
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))

@v2.get("/users/{user_id}/subscriptions")
def read_user_subscriptions(user_id: int, db: Session = Depends(get_db)):
    try:
        user = crud.get_user(db, user_id=user_id)
        if user is None:
            return generate_response(data=None, status_code=404, message="用户不存在")
        
        subscriptions = user.subscriptions
        subscription_data = [
            {
                "id": sub.id,
                "name": sub.subscription.name,
                "description": sub.subscription.description,
                "points_cost": sub.subscription.points_cost
            } for sub in subscriptions
        ]
        
        return generate_response(subscription_data, 200, "成功获取用户订阅")
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))

# 订阅 CRUD
@v2.post("/subscriptions/")
def create_subscription(subscription: schemas.SubscriptionCreate, db: Session = Depends(get_db)):
    try:
        result = crud.create_subscription(db=db, subscription=subscription)
        return generate_response(result, 200, "成功")
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))

@v2.get("/subscriptions/")
def read_subscriptions(page: int = 1, num: int = 10, db: Session = Depends(get_db)):
    try:
        skip = (page - 1) * num
        subscriptions = crud.get_subscriptions(db, skip=skip, limit=num)
        return generate_response(subscriptions, 200, "成功")
    except Exception as e:
        logger.error(traceback.format_exc())
        return generate_response({}, 500, str(e))

@v2.get("/subscriptions/{subscription_id}")
def read_subscription(subscription_id: int, db: Session = Depends(get_db)):
    db_subscription = crud.get_subscription(db, subscription_id=subscription_id)
    if db_subscription is None:
        return generate_response(data=None, status_code=404, message="订阅不存在")
    return db_subscription

@v2.put("/subscriptions/{subscription_id}")
def update_subscription(subscription_id: int, subscription: schemas.SubscriptionUpdate, db: Session = Depends(get_db)):
    try:
        db_subscription = crud.get_subscription(db, subscription_id=subscription_id)
        if db_subscription is None:
            return generate_response(data=None, status_code=404, message="订阅不存在")
        result = crud.update_subscription(db=db, subscription_id=subscription_id, subscription=subscription)
        return generate_response(result, 200)
    except Exception as e:
        return generate_response({}, 500, str(e))

@v2.delete("/subscriptions/{subscription_id}")
def delete_subscription(subscription_id: int, db: Session = Depends(get_db)):
    try:
        db_subscription = crud.get_subscription(db, subscription_id=subscription_id)
        if db_subscription is None:
            return generate_response(data=None, status_code=404, message="订阅不存在")
        result = crud.delete_subscription(db=db, subscription_id=subscription_id)
        return generate_response(result, 200)
    except Exception as e:
        return generate_response(data=None, status_code=500, message=str(e))

# 管理员邮箱 CRUD
@v2.post("/admin_emails/")
def create_admin_email(admin_email: schemas.AdminEmailCreate, db: Session = Depends(get_db)):
    try:
        result = crud.create_admin_email(db=db, admin_email=admin_email)
        return generate_response(result, 200)
    except Exception as e:
        return generate_response({}, 500, str(e))

@v2.get("/admin_emails/")
def read_admin_emails(page: int = 1, num: int = 10, db: Session = Depends(get_db)):
    try:
        skip = (page - 1) * num
        admin_emails = crud.get_admin_emails(db, skip=skip, limit=num)
        return generate_response(admin_emails, 200)
    except Exception as e:
        return generate_response({}, 500, str(e))

@v2.get("/admin_emails/{admin_email_id}")
def read_admin_email(admin_email_id: int, db: Session = Depends(get_db)):
    db_admin_email = crud.get_admin_email(db, admin_email_id=admin_email_id)
    if db_admin_email is None:
        return generate_response(data=None, status_code=404, message="管理员邮箱不存在")
    return db_admin_email

@v2.put("/admin_emails/{admin_email_id}")
def update_admin_email(admin_email_id: int, admin_email: schemas.AdminEmailUpdate, db: Session = Depends(get_db)):
    try:
        db_admin_email = crud.get_admin_email(db, admin_email_id=admin_email_id)
        if db_admin_email is None:
            return generate_response(data=None, status_code=404, message="管理员邮箱不存在")
        result = crud.update_admin_email(db=db, admin_email_id=admin_email_id, admin_email=admin_email)
        return generate_response(result, 200)
    except Exception as e:
        return generate_response({}, 500, str(e))

@v2.delete("/admin_emails/{admin_email_id}")
def delete_admin_email(admin_email_id: int, db: Session = Depends(get_db)):
    try:
        db_admin_email = crud.get_admin_email(db, admin_email_id=admin_email_id)
        if db_admin_email is None:
            return generate_response(data=None, status_code=404, message="管理员邮箱不存在")
        result = crud.delete_admin_email(db=db, admin_email_id=admin_email_id)
        return generate_response(result, 200)
    except Exception as e:
        return generate_response({}, 500, str(e))

